<?php

namespace IDock\Insurance\JDAL\Bean;

use Exception;
use IDock\IDock\IDockEnums;
use IDock\Insurance\JDAL\JDALEnums;
use IDock\Visitor\NonCar\NonCarProductListVisitor;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;
use IDock\Visitor\Premium\PremiumRelationVisitor;

class BasePremiumInquiry
{

    /**
     * orderId
     * @var  $orderId
     */
    public $orderId;

    public $partnerRef;

    /**
     * 产品类型
     * @var  $productLine
     */
    public $productLine;

    /**
     * 条款体系代码
     * @var  $clauseType
     */
    public $clauseType;

    /**
     * 产品体系
     * @var  $productType
     */
    public $productType;

    /**
     * 使用性质
     * @var  $motorUsageTypeCode
     */
    public $motorUsageTypeCode;

    /**
     * 车辆种类
     * @var  $motorTypeCode
     */
    public $motorTypeCode;

    /**
     * 车辆类型
     * @var  $commVehSubtype
     */
    public $commVehSubtype;

    public $basePart = [];

    public $vehicle = [];

    public $owner = [];

    public $policyParties = [];

    public $coverageItemList = [];

    public $vehicleTaxation = [];

    protected $visitor;

    public function __construct($visitor)
    {
        $this->visitor = $visitor;
    }

    /**
     * 初始化
     * @return void
     * @throws Exception
     */
    public function init()
    {
        $this->orderIdAndPartnerRef();
        $this->productLine();
        $this->clauseAndProductType();
        $this->motorUsageTypeCode();
        $this->motorTypeCode();

    }

    public function queryInit()
    {
        $this->basePart();
        $this->vehicle();
        $this->owner();
        $this->policyParties();
        $this->coverageItemList();
        $this->vehicleTaxation();
    }

    private function orderIdAndPartnerRef()
    {
        if ($this->visitor instanceof PremiumInquiryVisitor) {
            $this->orderId = $this->visitor->getVehicleVisitor()->argc['orderId'] ?? '';
            $this->partnerRef = $this->visitor->getExtInfoVisitor()->argc['channelCode'] ?? '';
        }

        if ($this->visitor instanceof NonCarProductListVisitor) {
            $this->partnerRef = $this->visitor->argc['channelCode'] ?? '';
        }
    }

    private function productLine()
    {
        $hasCi = $hacBi = false;

        if ($this->visitor instanceof PremiumInquiryVisitor) {
            $hacBi = $this->visitor->biStartData;
            $hasCi = $this->visitor->ciStartData;
        }

        if ($this->visitor instanceof NonCarProductListVisitor) {
            $hacBi = $this->visitor->hasCi;
            $hasCi = $this->visitor->hasBi;
        }

        if ($hacBi and $hasCi) {
            $this->productLine = 'All';
            return;
        }

        if ($hasCi) {
            $this->productLine = '710';
            return;
        }

        if ($hacBi) {
            $this->productLine = '701';
            return;
        }
    }

    private function clauseAndProductType()
    {
        $isNewEnergy = false;


        if ($this->visitor instanceof PremiumInquiryVisitor) {
            /*** @var  PremiumInquiryVisitor $visitor */
            $isNewEnergy = $this->visitor->getVehicleVisitor()->isNewEnergy;
        }

        if ($this->visitor instanceof NonCarProductListVisitor) {
            /*** @var  NonCarProductListVisitor $visitor */
            $energyTypeCode = $this->visitor->energyTypeCode;
            if ($energyTypeCode == 'E02' or $energyTypeCode == 'E04') {
                $isNewEnergy = true;
            }
        }

        if ($isNewEnergy) {
            //新能源
            $this->clauseType = '04';
            $this->productType = '0401';
        } else {
            //机动车
            $this->clauseType = '03';
            $this->productType = '0301';
        }
    }

    //使用性质
    private function motorUsageTypeCode()
    {
        if ($this->visitor instanceof PremiumInquiryVisitor) {
            /*** @var  PremiumInquiryVisitor $visitor */
            $vehicleVisitor = $this->visitor->getVehicleVisitor();
        }

        if ($this->visitor instanceof NonCarProductListVisitor) {
            /*** @var  NonCarProductListVisitor $visitor */
            $vehicleVisitor = $this->visitor;
        }

        if (!isset($vehicleVisitor)) {
            return;
        }

        $code = $vehicleVisitor->useNatureCode . $vehicleVisitor->attachNature . $vehicleVisitor->carKindCode;

        switch ($code) {
            case '0101100': //非营业个人客车
                $this->motorUsageTypeCode = '701';
                return;
            case '0103100': //非营业企业客车
                $this->motorUsageTypeCode = '702';
                return;
            case '0102100': //非营业机关客车
                $this->motorUsageTypeCode = '703';
                return;
            case '0101200': //非营业个人货车
            case '0101300': //非营业个人低速货车
            case '0102200': //非营业机关货车
            case '0102300': //非营业机关低速货车
            case '0103200': //非营业企业货车
            case '0103300': //非营业企业低速货车
                $this->motorUsageTypeCode = '704';
                return;
            case '0201200': //营业个人货车
            case '0202200': //营业机关货车
            case '0203200': //营业企业货车

            case '0201300': //营业个人低速货车
            case '0202300': //营业机关低速货车
            case '0203300': //营业企业低速货车
                $this->motorUsageTypeCode = '708';
                return;
        }

        //营业出租
        if ($vehicleVisitor->useNatureCode == '02' and $vehicleVisitor->causeType == '004') {
            $this->motorUsageTypeCode = '705';
            return;
        }

        //营业公交
        if ($vehicleVisitor->useNatureCode == '02' and $vehicleVisitor->causeType == '006') {
            $this->motorUsageTypeCode = '706';
            return;
        }

        //营业客运
        if ($vehicleVisitor->useNatureCode == '02' and $vehicleVisitor->causeType == '007') {
            $this->motorUsageTypeCode = '707';
            return;
        }
    }

    //车辆种类
    private function motorTypeCode()
    {
        $seat = 0;
        if ($this->visitor instanceof PremiumInquiryVisitor) {
            /*** @var  PremiumInquiryVisitor $visitor */
            $vehicleVisitor = $this->visitor->getVehicleVisitor();
            $seat = $vehicleVisitor->vehicleSeat;
        }

        if ($this->visitor instanceof NonCarProductListVisitor) {
            /*** @var  NonCarProductListVisitor $visitor */
            $vehicleVisitor = $this->visitor;
            $seat = $vehicleVisitor->seats;
        }

        if (!isset($vehicleVisitor)) {
            return;
        }

        //客车
        if ($vehicleVisitor->carKindCode == '100') {
            $this->commVehSubtype = 'PC';

            if ($seat < 6) {
                $this->motorTypeCode = '11';
                return;
            }

            if ($seat < 10) {
                $this->motorTypeCode = '12';
                return;
            }
            if ($seat < 20) {
                $this->motorTypeCode = '13';
                return;
            }

            if ($seat < 36) {
                $this->motorTypeCode = '14';
                return;
            }

            if ($seat > 36) {
                $this->motorTypeCode = '15';
                return;
            }

        }

        //低速载货汽车
        if ($vehicleVisitor->carKindCode == '210') {
            $this->motorTypeCode = '93';
            $this->commVehSubtype = 'TR';
            return;
        }

        //货车
        if ($vehicleVisitor->carKindCode == '200') {
            $this->commVehSubtype = 'TR';

            if ($vehicleVisitor->vehicleTonnage < 2000) {
                $this->motorTypeCode = '21';
                return;
            }

            if ($vehicleVisitor->vehicleTonnage < 5000) {
                $this->motorTypeCode = '22';
                return;
            }

            if ($vehicleVisitor->vehicleTonnage < 10000) {
                $this->motorTypeCode = '23';
                return;
            }

            if ($vehicleVisitor->vehicleSeat > 10000) {
                $this->motorTypeCode = '24';
                return;
            }
        }

        throw new Exception('未知的车辆种类--京东');
    }

    //-------------


    private function basePart()
    {
        if ($this->visitor instanceof PremiumInquiryVisitor) {

            if ($this->visitor->ciStartData) {
                $this->visitor->ciEndData = date('Y-m-d H:i:s', strtotime('+1 year', strtotime($this->visitor->ciStartData)));
            }

            if ($this->visitor->biStartData) {

                if (date('H', strtotime($this->visitor->biStartData)) != '00') {
                    $this->visitor->biEndData = date('Y-m-d 00:00:00', strtotime('+1 year +1day', strtotime($this->visitor->biStartData)));
                } else {
                    $this->visitor->biEndData = date('Y-m-d 00:00:00', strtotime('+1 year', strtotime($this->visitor->biStartData)));
                }
            }

            $this->basePart = [
                'orderId' => $this->orderId,
                'productLine' => $this->productLine,
                'clauseType' => $this->clauseType,
                'productType' => $this->productType,
                'argumentSolution' => '22', //目前版本传固定值22，诉讼
                'ctplEffectiveDate' => $this->visitor->getCiStartData(),
                'ctplExpireDate' => $this->visitor->getCiEndData(),
                'commEffectiveDate' => $this->visitor->getBiStartData(),
                'commExpireDate' => $this->visitor->getBiEndData(),
                'comCode' => $this->visitor->getExtInfoVisitor()->argc['comCode'] ?? '',
                'partnerRef' => $this->partnerRef,
            ];
        }
    }

    private function vehicle()
    {
        if ($this->visitor instanceof PremiumInquiryVisitor) {
            $vehicleArgc = $this->visitor->getVehicleVisitor()->argc;

            $vehicleVisitor = $this->visitor->getVehicleVisitor();

            $data = [
                'vehicleCode' => $vehicleArgc['vehicleCode'] ?? '',
                'modelCode' => $vehicleArgc['modelCode'] ?? '',
                'bodyType' => $vehicleArgc['bodyType'] ?? '',
                'make' => $vehicleArgc['make'] ?? '',
                'displacement' => $vehicleVisitor->vehicleExhaust ? (string)($this->visitor->getVehicleVisitor()->vehicleExhaust * 1000) : '',
                'ratedPassengerCapacity' => $vehicleVisitor->argc['seatingCapacity'] ?? '',

                'motorUsageTypeCode' => $this->motorUsageTypeCode,
                'licensePlateType' => $vehicleVisitor->licenseTypeCode,
                'motorTypeCode' => $this->motorTypeCode,

                'licensePlateNo' => $vehicleVisitor->licenseNo,
                'noLicenseFlag' => $vehicleVisitor->isNewVehicle ? '1' : '0',
                'firstRegisterDate' => $vehicleVisitor->firstRegisterDate,
                'vinNo' => $vehicleVisitor->vin,
                'engineNo' => $vehicleVisitor->engineNo,
                'vehicleType' => $vehicleVisitor->vehicleStyleCode,

                'newCarValue' => $vehicleArgc['newCarValue'] ?? '',
                'fuelType' => JDALEnums::$energyType[$vehicleVisitor->energyTypeCode],
                'wholeWeight' => $vehicleVisitor->wholeWeight,

                'chgOwnerFlag' => (string)($vehicleVisitor->isTransfer),
                'ecdemicVehicleFlag' => $vehicleVisitor->nonlocalCar,
                'loanVehicleFlag' => '0', //是否车贷投保多年标志
                'tonnage' => $vehicleVisitor->vehicleTonnage,

                'transferDate' => $vehicleVisitor->transferDate,

                'remark' => '', //档位，手动档
                'carAge' => '', //车龄
                'carActualValue' => '', //车辆实际价值
                'carName' => $vehicleArgc['carName'] ?? '', //车辆型号
                'model' => $vehicleArgc['model'] ?? '',
                'newVehicle' => $this->visitor->getVehicleVisitor()->isNewVehicle ? '1' : '0',
                'madeDate' => '',
                'partnerRef' => $this->partnerRef,
                'seatingCapacity' => $vehicleVisitor->vehicleSeat,

                'bodyTypePrinted' => $vehicleVisitor->vehicleModel,
            ];

            //新车备案
            if ($this->visitor->vehicleVisitor->carCertificateType) {
                $data['certificateType'] = $this->visitor->vehicleVisitor->carCertificateType;
                $data['certificateNo'] = $this->visitor->vehicleVisitor->carCertificateNo;
                $data['certificateDate'] = $this->visitor->vehicleVisitor->carCertificateDate ? date('Y-m-d',strtotime($this->visitor->vehicleVisitor->carCertificateDate)) : '';
            }

            //交强险过户
            if ($vehicleVisitor->isCiTransfer) {
                $data['specialCarFlag'] = '1';
            }

            //免验车
            if ($this->visitor->getExtInfoVisitor()->carCheckCode == 'CS2') {
                $data['vehicleCheckFlag'] = '0';
            }

            //已验车
            if ($this->visitor->getExtInfoVisitor()->carCheckCode == 'CS3') {
                $data['vehicleCheckFlag'] = '1';
                $data['vehicleCheckOperator'] = $this->visitor->getExtInfoVisitor()->carChecker;
                $data['vehicleCheckDate'] = $this->visitor->getExtInfoVisitor()->carCheckDate;
                $data['statusOfCheck'] = '已验车';
            }

            $this->vehicle = $data;
        }
    }

    private function owner()
    {
        if ($this->visitor instanceof PremiumInquiryVisitor) {

            $owner = $this->visitor->getOwnerVisitor();
            $data = [
                'ownerType' => $owner->typeCode == 'R1' ? '1' : '3',
                'ownerName' => $owner->name,
                'credentialCode' => JDALEnums::$certificateTypeCode[$owner->certificateTypeCode],
                'credentialNo' => $owner->certificateNo,
                'credentialStart' => $owner->certificateStartDate,
                'credentialEnd' => $owner->certificateEndDate,
                'longTermCredential' => $owner->certificateEndDate == '9999-12-31' ? '1' : '0',
                'contactAddress' => $owner->address,
            ];

            if (!$data['credentialCode']) {
                throw new Exception('不支持的证件类型');
            }

            $this->owner = $data;
        }
    }

    /**
     * 关系人
     */
    private function policyParties()
    {
        if (!$this->visitor instanceof PremiumInquiryVisitor) {
            return;
        }

        $insuredData = $this->insuredData($this->visitor->getInsuredVisitor(), 'PHI');

        $applicantData = $this->insuredData($this->visitor->getApplicantVisitor(), 'PRP');

        $list = [
            $insuredData,
            $applicantData,
        ];

        $this->policyParties = $list;
    }

    /**
     * 投保人 被保人信息
     * @param PremiumRelationVisitor $visitor
     * @param $type
     * @return array
     */
    private function insuredData(PremiumRelationVisitor $visitor, $type): array
    {
        //被保人
        $data = [
            'roleType' => $type, //被保人
            'customerNameText' => $visitor->name,
            'customerType' => $visitor->typeCode == 'R1' ? '1' : '3',
            'customerNatureCode' => '9',
            'credentialCode' => JDALEnums::$certificateTypeCode[$visitor->certificateTypeCode],
            'credentialNo' => $visitor->certificateNo,
            'credentialStart' => $visitor->certificateStartDate,
            'credentialEnd' => $visitor->certificateEndDate,
            'longTermCredential' => $visitor->certificateEndDate == '9999-12-31' ? '1' : '0',
            'contactAddress' => $visitor->address,
            'email' => $visitor->email,
            //'issuer' => '成都公安局', //签发机构,
            //'nation' => '汉', //民族,
            'phoneNo' => $visitor->mobile,
            'sameWithOwner' => '0', //是否同车主
            'invoiceType' => '05',
            'needEinvoice' => 'N',
        ];

        if ($this->visitor->getOwnerVisitor()->certificateNo == $visitor->certificateNo) {
            $data['sameWithOwner'] = '1';
            $data['customerNatureCode'] = '1';
        }

        return $data;
    }

    /**
     * 险种信息
     * @return void
     * @throws Exception
     */
    private function coverageItemList()
    {
        if (!$this->visitor instanceof PremiumInquiryVisitor) {
            return;
        }

        $list = [];

        foreach ($this->visitor->getCoverageVisitorList() as $value) {
            /*** @var $value PremiumCoverageVisitor */

            $item = [];
            //去除交强险
            if ($value->coverageCode == 'C01001') {
                continue;
            }

            //险种代码
            $coverageCode = JDALEnums::$coverageCode[$value->coverageCode];

            if (!$coverageCode) {
                throw new Exception('不支持的险种.' . IDockEnums::$coverageCode[$value->coverageCode]);
            }

            //险种性质代码
            $coverageClassCode = JDALEnums::$coverageClassCode[$this->productType][$coverageCode] ?? '2';

            //保额
            $sumLimit = $value->amount;

            //车损
            if ($coverageCode == 'MH') {
                $sumLimit = $this->visitor->getVehicleVisitor()->argc['newCarValue'] ?? '';
            }

            //附加乘客
            if ($coverageCode == 'MLPL' or $coverageCode == 'EMPL') {
                $sumLimit = (string)($value->amount * ($this->visitor->getVehicleVisitor()->vehicleSeat - 1));
            }

            //维修期间补偿
            if ($coverageCode == 'RC') {
                $item['compensationDays'] = $value->quantity;
                $item['dailyCompensation'] = $value->unitAmount;

                $sumLimit = (string)($value->quantity * $value->unitAmount);
            }

            //服务次数
            if ($value->serviceTimes) {
                $item['serviceTimes'] = $value->serviceTimes;
            }
            //绝对免赔率
            if (in_array($coverageCode, ['ANPL','ANDL','ANMH','ANTPL'])) {
                $sumLimit = (string)($value->deductionRate / 100);
                $item['defaultDiscount'] = $sumLimit;
            }
            //新增设备险
            if ($coverageCode == 'AA') {
                $sumLimit = (string)(array_sum(array_column($this->visitor->deviceList,'actualValue')));
            }
            
            //保外医疗保额验证
            if (in_array($coverageCode,['EMPL','EMDL','EMTPL'])) {
                $coverageName = IDockEnums::$coverageCode[$value->coverageCode];
                
                if (!in_array($value->amount,['10000','20000','50000','100000'])) {
                    throw new Exception($coverageName.'保额只能选择 1万,2万,5万,10万');
                }
            }

            $item['coverageClassCode'] = $coverageClassCode;
            $item['coverageCode'] = $coverageCode;
            $item['coverageName'] = IDockEnums::$coverageCode[$value->coverageCode];
            $item['sumLimit'] = $sumLimit;
            $item['isNonDeductible'] = 'N'; //是否投保不计免赔

            $list[] = $item;
        }

        $this->coverageItemList = $list;
    }

    /**
     * 车船税
     */
    private function vehicleTaxation()
    {
        if (!$this->visitor instanceof PremiumInquiryVisitor) {
            return;
        }
        $visitor = $this->visitor->getCarTaxVisitor();
        $data = [
            'taxConditionCode' => JDALEnums::$taxTypeCode[$visitor->taxTypeCode],
            'taxPayerIdentificationCode' => $visitor->taxpayerCertificateNo,
            'taxPayerName' => $visitor->taxpayerName,
            'taxpayerCredentialCode' => JDALEnums::$certificateTypeCode[$visitor->taxpayerCertificateTypeCode],
            'taxPaymentMark' => '',
            'currentTaxDue' => []
        ];

        //完税
        if ($visitor->taxTypeCode == 'T03') {
            $data['currentTaxDue'] = [
                'VehiclePaidTaxation' => [
                    'taxDepartmentCode' => $visitor->taxDepartmentCode,
                    'taxDepartment' => $visitor->taxDepartment,
                    'taxDocumentNumber' => $visitor->taxDocumentNumber,
                    'taxDocumentDate' => $visitor->taxStartDate,
                    'taxPaidAreaCode' => $visitor->taxPaidAreaCode,
                ]
            ];
        }

        //减 免税
        if ($visitor->taxTypeCode == 'T03' or $visitor->taxTypeCode == 'T04') {
            $data['currentTaxDue'] = [
                'derateTaxation' => [
                    'deductionDocumentNumber' => $visitor->taxDocumentNumber,
                    'taxDepartmentCode' => $visitor->taxDepartmentCode,
                    'taxDepartment' => $visitor->taxDepartment
                ]
            ];
        }

        $this->vehicleTaxation = $data;
    }

}
